package com.zyj.test.month1.day8;

import java.util.Arrays;

/**
 * @author Yijia Zhang
 * @create 2024-05-15 22:27
 */
public class code0016 {
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int minDif = Integer.MAX_VALUE;
        int res = -1;
        for (int i = 0; i < nums.length - 2; i++) {
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }
            int l = i + 1;
            int r = nums.length - 1;
            int num = nums[i];
            int dif = target - num;
            while (l < r) {
                int sum = nums[l] + nums[r];
                int abs = Math.abs(target - num - sum);
                if (abs < minDif) {
                    res = sum + num;
                    minDif = abs;
                }
                if (sum < dif) {
                    l++;
                } else if (sum > dif) {
                    r--;
                } else {
                    return target;
                }
            }
        }
        return res;
    }
}
